<template>
	<view style="background-color: #f8f8f8;height: 100vh;">
		<cu-custom :isBack="false"></cu-custom>
		<scroll-view scroll-y="true" class="scrollPage" :style="[{marginBottom:`${tabbarHeight}px`}]">
			<view class="padding-top" :style="{background:themeConfig.commonColor}">
				<view class="content flex justify-between margin-top-xs">
					<view class="padding-bottom flex">
						<view v-if="isLogin" class="cu-avatar xl round margin-left bg-gray"
							:style="[{backgroundImage:`url(${iconUrl})`}]">
						</view>
						<view v-else class="cu-avatar xl round margin-left bg-gray">
							<text class="cuIcon-people text-sl text-white"></text>
						</view>

						<view class=" margin-left margin-top-xs">
							<view v-if="isLogin" @tap="goToLogin" class="text-lg">
								<text class="margin-right-sm">{{$t('hi')}}</text>
								<text>{{userName}}</text>
							</view>
							<button v-else class="cu-btn round lines-grey shadow"
								@tap="goToLogin">{{$t('login')}}</button>
							<view class="text-gray margin-top-sm text-df">{{$t('device')+$t('count')}}:{{allDeviceCount}}</view>
						</view>
					</view>
					<view class="flex justify-end padding-top-xs padding-lr-xl" @tap="goToMoreOperate()">
						<text class="cuIcon-settings text-grey" style="font-size:20px;"></text>
					</view>
				</view>
				<view class="cu-list grid col-4 no-border text-black"
					style="background:rgba(0,0,0,0);padding:10px 0px;">
					<view class="cu-item" v-for="(item,index) in deviceStatusList" :key="index">
						<view class="text-lg padding-xs" :style="{color:themeConfig.primaryColor}">{{item.num}}</view>
						<view class="text-gray text-lg">{{$t(item.status)}}</view>
					</view>
				</view>
			</view>

			<view class="shadow-warp bg-white margin-left-sm margin-right-sm"
				style="border-radius:10px;margin-top:15px;">
				<view class="cu-bar bg-white solid-bottom"
					style="border-top-left-radius:10px;border-top-right-radius:10px;" @tap="goToMoreOperate()">
					<view class="action">
						<text class="text-bold ztnCustom-color-black">{{$t('more')}}</text>
					</view>
					<!-- <view class="action">
					<text class="cuIcon-right"></text>
				</view> -->
				</view>
				<view class="cu-list grid col-4 no-border" style="background:rgba(0,0,0,0)">
					<view class="cu-item" @tap="tapCommonScanHandle()">
						<view class="cuIcon-scan text-xxl" :style="{color : themeConfig.primaryColor}"></view>
						<view class="padding-xs text-df">{{$t('scan')}}</view>
					</view>
					<view class="cu-item" @tap="bindDeviceModal()">
						<view class="cuIcon-cascades text-xxl" :style="{color : themeConfig.primaryColor}"></view>
						<view class="padding-xs text-df">{{$t('bind')+$t('device')}}</view>
					</view>
					<view class="cu-item" @tap="gotoUserInfo()">
						<view class="cuIcon-profile text-xxl" :style="{color : themeConfig.primaryColor}"></view>
						<view class="padding-xs text-df">{{$t('user')+$t('info')}}</view>
					</view>
					<view class="cu-item" @tap="gotoUserLoginLog()">
						<view class="cuIcon-group text-xxl" :style="{color : themeConfig.primaryColor}"></view>
						<view class="padding-xs text-df">{{$t('login')+$t('log')}}</view>
					</view>
					<view class="cu-item" @tap="tapCurrentVersion()">
						<view class="cuIcon-info text-xxl" :style="{color : themeConfig.primaryColor}"></view>
						<view class="padding-xs text-df">{{$t('version')}}</view>
					</view>
					<view class="cu-item" @tap="gotoCompanyArticle()">
						<view class="cuIcon-read text-xxl" :style="{color : themeConfig.primaryColor}"></view>
						<view class="padding-xs text-df">{{$t('article')}}</view>
					</view>
					<view class="cu-item" @tap="gotoDoc()">
						<view class="cuIcon-question text-xxl" :style="{color : themeConfig.primaryColor}"></view>
						<view class="padding-xs text-df">{{$t('doc')}}</view>
					</view>
					<view class="cu-item" @tap="gotoWorkOrder()">
						<view class="cuIcon-service text-xxl" :style="{color : themeConfig.primaryColor}"></view>
						<view class="padding-xs text-df">{{$t('workOrder')}}</view>
					</view>
				</view>
			</view>

			<view class="shadow-warp bg-white margin-left-sm margin-right-sm"
				style="border-radius:10px;margin-top:15px;">
				<view class="cu-list grid col-4 no-border" style="background:rgba(0,0,0,0) ">
					<view class="cu-item" style="margin:-10px 0">
						<picker @change="languagePickerChange" :value="currentLanguageIndex" :range="languageList"
							range-key="label">
							<view class="cuIcon-font text-xxl" :style="{color : themeConfig.primaryColor}"></view>
							<view class="padding-xs text-df">{{$t('language')}}</view>
							<view class="text-gray text-xs" v-if="isLogin">
								{{formatLanguageIndex(currentLanguageIndex).label}}
							</view>
						</picker>
					</view>
					<view class="cu-item" style="margin:-10px 0">
						<picker @change="themePickerChange" :value="currentThemeIndex" :range="themeList"
							range-key="label">
							<view class="cuIcon-paint text-xxl" :style="{color : themeConfig.primaryColor}"></view>
							<view class="padding-xs text-df">{{$t('theme')}}</view>
							<view class="text-gray text-xs" v-if="isLogin">{{formatThemeIndex(currentThemeIndex).label}}
							</view>
						</picker>
					</view>
					<view class="cu-item" style="margin:-10px 0" @tap="modifyModal()">
						<view class="cuIcon-post text-xxl" :style="{color : themeConfig.primaryColor}"></view>
						<view class="padding-xs text-df">{{$t('update')+$t('password')}}</view>
					</view>
					<view v-if="isLogin" class="cu-item" @tap="tapLogout" style="margin:-10px 0">
						<view class="cuIcon-exit text-xxl text-red"></view>
						<view class="padding-xs text-df">{{$t('logout')}}</view>
					</view>
					<view v-else class="cu-item" @tap="goToLogin" style="margin:-10px 0">
						<view class="cuIcon-friendadd text-xxl text-red"></view>
						<view class="padding-xs text-df">{{$t('login')}}</view>
					</view>
				</view>
			</view>
			<view :style="[{height:`${tabbarHeight}px`}]"></view>

			<view v-if="isShowBindDeviceModal" class="cu-modal bottom-modal" :class="[isShowBindDeviceModal?'show':'']"
				style="text-align: start" :style="[{bottom:`${tabbarHeight}px`}]">
				<view class="cu-dialog bg-white">
					<view class="cu-bar bg-white">
						<view class='action text-bold'>
							{{$t('bind')+$t('device')}}
						</view>
						<view class='action text-bold'>
							<view class="cuIcon-close text-grey" @tap="bindDeviceModal"></view>
						</view>
					</view>
					<form @submit='bindDevice'>
						<view class="cu-form-group" style="border-bottom: 1px solid #eee;">
							<view class="title">{{$t('deviceCore')}}</view>
							<input type="text" :placeholder="$t('deviceCore')"
								 name="deviceCore" />
							<view class="cuIcon-scan" :style="{color : themeConfig.primaryColor}"
								@tap="tapBindDeviceScanHandle()"></view>
						</view>
						<button :style="{'--color': themeConfig.primaryColor}" class="cu-btn block margin lg"
							form-type="submit">{{$t('confirm')}}</button>
					</form>
				</view>
			</view>

			<view class="cu-modal bottom-modal" :class="[isShowModifyModal?'show':'']" style="text-align: start;"
				:style="[{bottom:`${tabbarHeight}px`}]">
				<view class="cu-dialog bg-white">
					<view class="cu-bar bg-white">
						<view class="action text-bold">
							{{$t('update')+$t('password')}}
						</view>
						<view class='action text-bold'>
							<view class="cuIcon-close text-grey" @tap="modifyModal"></view>
						</view>
					</view>
					<form>
						<view class="cu-form-group">
							<view class="title">{{$t('old')+$t('password')}}</view>
							<input type="password" v-model="oldPassword" />
						</view>
						<view class="cu-form-group" style="border-bottom: 1px solid #eee;">
							<view class="title">{{$t('new')+$t('password')}}</view>
							<input type="password" v-model="newPassword" />
						</view>
						<button :style="{'--color': themeConfig.primaryColor}" class="cu-btn block margin lg"
							@tap="modifyPassword" form-type="reset">{{$t('confirm')}}</button>
					</form>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		showToast,
		showModal
	} from '@/util/toast.js'
	import {
		commonScanHandle,
		parseUrl
	} from '@/util/utils.js'
	import {
		listLanguage,
		listTheme
	} from '@/util/dataUtil.js'
	import * as authUserApi from '@/api/auth/authUserApi.js'
	import * as ztnNativeFunction from '@/util/ztnNativeFunction.js'
	import * as iotDeviceApi from '@/api/iot/iotDeviceApi.js'
	import *
	as iotDeviceBelongApi from '@/api/iot/iotDeviceBelongApi.js'
	import * as authTokenApi from '@/api/auth/authTokenApi.js'
	import myConfig from '@/myConfig.js'
	import * as storage from '@/util/storage.js'
	export default {
		name:'Center',
		data() {
			return {
				isLogin: true,
				userName: '',
				iconUrl: '',
				deviceStatusList: [],
				deviceStatusNumberList: [0, 0, 0, 0],
				currentLanguageIndex: 0,
				currentThemeIndex: 0,
				isShowModifyModal: false,
				oldPassword: '',
				newPassword: '',
				isShowBindDeviceModal: false,
				allDeviceCount: 0,
				tabbarHeight: storage.getTabbarHeight(),
				languageList: [],
				themeList: [],
				userId: storage.getUserId(),
				scanModel: null,
				websiteModel: storage.getWebsiteModel()
			}
		},
		name: 'center',
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		emits:['language-change','un-login'],
		mounted() {
			authTokenApi.checkLogin().then(res => {
				const {
					data
				} = res
				if (data) {
					this.init()
					this.isLogin = true
				} else {
					this.isLogin = false
					this.getUnLoginDeviceStatusCount()
				}
			})
		},
		methods: {
			formatLanguageIndex(index) {
				return this.languageList[index]
			},
			formatThemeIndex(index) {
				return this.themeList[index]
			},
			gotoCompanyArticle() {
				uni.navigateTo({
					url: `/pages/articleList/articleList`
				})
			},
			gotoWorkOrder() {
				uni.navigateTo({
					url: `/pages/workOrderList/workOrderList`
				})
			},
			gotoDoc() {
				uni.navigateTo({
					url: `/pages/docList/docList`
				})
			},
			bindDeviceModal() {
				this.isShowBindDeviceModal = !this.isShowBindDeviceModal
			},
			bindDevice(e) {
				const deviceCore = e.detail.value.deviceCore.replace(/\s/g, '')
				this.isShowBindDeviceModal = false
				iotDeviceApi.bindDeviceUser({
					deviceCore: deviceCore,
					userName: this.userName
				}).then((res) => {
					if (res.data) {
						showToast(this.$t('success'), 'none', 1000, false)
					} else {
						showToast(this.$t('failure'), 'none', 1000, false)
					}
				})
			},
			init: async function() {
				this.languageList = listLanguage(this)
				this.listStatusCount()
				this.userName = storage.getUserName()
				this.iconUrl = storage.getUserIconUrl()
				const language = storage.getLanguage()
				const theme = storage.getTheme()
				this.themeList = listTheme(this, language)
				for (let i in this.languageList) {
					const item = this.languageList[i]
					if (language === item.value) {
						this.currentLanguageIndex = i
						break
					}
				}
				for (let i in this.themeList) {
					const item = this.themeList[i]
					if (theme === item.value) {
						this.currentThemeIndex = i
						break
					}
				}
			},
			modifyModal() {
				this.isShowModifyModal = !this.isShowModifyModal
			},
			modifyPassword(e) {
				const oldPassword = this.oldPassword.replace(/\s/g, '')
				const newPassword = this.newPassword.replace(/\s/g, '')
				if (oldPassword.length < 6 || newPassword.length < 6) {
					showToast(this.$t('passwordLeastLengthTip'), 'none', 1000, false)
				} else if (oldPassword === newPassword) {
					showToast(this.$t('password') + this.$t('equal'), 'none', 1000, false)
				} else {
					authUserApi.updateUser({
						userId: this.userId,
						oldPassword: oldPassword,
						password: newPassword,
					}).then((res) => {
						if (res.data) {
							this.modifyModal()
							showToast(this.$t('success'), 'none', 1000, false)
						} else {
							showToast(this.$t('failure'), 'none', 1000, false)
						}
					})
					this.oldPassword = ''
					this.newPassword = ''
				}
			},
			goToLogin(e) {
				uni.reLaunch({
					url: `/pages/login/login`
				});
			},
			getUnLoginDeviceStatusCount() {
				for (let i = 0; i < this.deviceStatusList.length; i++) {
					this.$set(this.deviceStatusList, i, {
						num: '--',
						status: '--'
					})
				}
			},
			listStatusCount() {
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.listStatusCountAll()
						break
					case 'company':
						api = iotDeviceApi.listStatusCountByCompany()
						break
					case 'dept':
						api = iotDeviceApi.listStatusCountByDept()
						break
					default:
						api = iotDeviceBelongApi.listStatusCount()
				}


				api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.deviceStatusList = data
						let allDeviceCount = 0
						for (let i = 0; i < data.length; i++) {
							allDeviceCount = allDeviceCount + data[i].num
						}
						this.allDeviceCount = allDeviceCount
					}
				})
			},
			tapCurrentVersion() {
				showModal(this.$t('version'), myConfig.app.version, false, this.$t('confirm'), this
					.$t('cancel'), (res) => {
						return
					})
			},
			gotoUserInfo() {
				uni.navigateTo({
					url: `/pages/userInfo/userInfo`
				})
			},
			gotoUserLoginLog() {
				uni.navigateTo({
					url: `/pages/userLoginLog/userLoginLog`
				})
			},
			tapCommonScanHandle() {
				this.scanModel = 'common'
				this.scanHandle()
			},
			tapBindDeviceScanHandle() {
				this.scanModel = 'bindDevice'
				this.scanHandle()
			},
			scanHandle() {
				// #ifdef H5
				ztnNativeFunction.scanErcode({
					success: (res) => {
						if (this.scanModel === 'common') {
							commonScanHandle(this, res)
						} else if (this.scanModel === 'bindDevice') {
							const param = parseUrl(res);
							if (param != null && param.deviceCore) {
								this.bindDevice({
									detail: {
										value: {
											deviceCore: param.deviceCore
										}
									}
								})
							} else {
								showToast(this.$t('qrcode') + this.$t('error'), 'none', 1000, false) //二维码有误
							}
						}

					},
					fail: (res) => {
						console.error(res)
						showToast(this.$t('failure'), 'none', 1000, false) //操作失败
					}
				})
				// #endif
				// #ifndef H5
				uni.scanCode({
					success: (res) => {
						if (this.scanModel === 'common') {
							commonScanHandle(this, res.result)
						} else if (this.scanModel === 'bindDevice') {
							const param = parseUrl(res.result);
							if (param != null && param.deviceCore) {
								this.bindDevice({
									detail: {
										value: {
											deviceCore: param.deviceCore
										}
									}
								})
							} else {
								showToast(this.$t('qrcode') + this.$t('error'), 'none', 1000, false) //二维码有误
							}
						}
					},
					fail: (res) => {
						showToast(this.$t('failure'), 'none', 1000, false) //操作失败
					}
				});
				// #endif
			},
			goToMoreOperate() {
				uni.navigateTo({
					url: `/pages/moreOperate/moreOperate`
				})
			},
			languagePickerChange(e) {
				this.currentLanguageIndex = parseInt(e.detail.value)
				const language = this.formatLanguageIndex(this.currentLanguageIndex).value
				storage.setLanguage(language)
				this.$i18n.locale = language
				this.$emit('language-change')
				this.init()
				showToast(this.$t('success'), 'none', 1000, false)
				if (this.isLogin) {
					authUserApi.updateUser({
						language: language,
						userId: this.userId
					})
				}
			},
			themePickerChange(e) {
				this.currentThemeIndex = e.detail.value
				const theme = this.formatThemeIndex(this.currentThemeIndex).value
				storage.setTheme(theme)
				this.$store.dispatch('setTheme', theme)
				showToast(this.$t('success'), 'none', 1000, false)
			},
			tapLogout() {
				const logout = this.$t('logout')
				const logoutContent = this.$t('confirm') + this.$t('logout') + '?'
				const confirmText = this.$t('confirm')
				const cancelText = this.$t('cancel')
				showModal(logout, logoutContent, true, confirmText, cancelText, (res) => {
					const openid = storage.getOpenid()
					authTokenApi.loginOut({}).then((res) => {
						storage.setOpenid(null)
						storage.setNickName(null)
						storage.setUserIconUrl(null)
						storage.setUserId(null)
						storage.setUserName(null)
						storage.setToken(null)
						this.isLogin = false
						this.allDeviceCount = 0
						showToast(this.$t('success'), 'success', 1000,
							false)
						this.$emit('un-login')
						this.getUnLoginDeviceStatusCount()
					})
				}, (res) => {
					return
				})
			}
		}
	}
</script>
<style>
</style>
